package com.atguigu.day05;

import com.atguigu.utils.ClickEvent;
import com.atguigu.utils.ClickSource;
import com.atguigu.utils.UrlViewCountPerWindow;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

// 增量聚合函数和全窗口聚合函数结合使用
public class Example1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new ClickSource())
                .keyBy(r -> r.url)
                .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                .aggregate(new CountAgg(), new WindowResult())
                .print();

        env.execute();
    }

    // 注意！！！输入泛型是Long，也就是getResult的返回值类型
    public static class CountAgg implements AggregateFunction<ClickEvent, Long, Long> {
        // 创建一个空累加器
        @Override
        public Long createAccumulator() {
            return 0L;
        }

        // 定义输入数据和累加器的聚合规则
        @Override
        public Long add(ClickEvent value, Long accumulator) {
            return accumulator + 1L;
        }

        // 窗口关闭时，获取累加结果，并输出
        @Override
        public Long getResult(Long accumulator) {
            return accumulator;
        }

        @Override
        public Long merge(Long a, Long b) {
            return null;
        }
    }

    public static class WindowResult extends ProcessWindowFunction<Long, UrlViewCountPerWindow, String, TimeWindow> {
        @Override
        public void process(String key, Context context, Iterable<Long> elements, Collector<UrlViewCountPerWindow> out) throws Exception {
            // 注意！！！迭代器中只有一个元素，就是CountAgg的getResult方法的返回值
            out.collect(new UrlViewCountPerWindow(
                    key,
                    elements.iterator().next(), // 取出迭代器中的唯一一个元素
                    context.window().getStart(),
                    context.window().getEnd()
            ));
        }
    }
}
